package com.bawei.module_live.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_live.databinding.ItemMoreLiveBinding
import com.bawei.module_live.data.LiveRoomData
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class LiveRoomAdapter : RecyclerView.Adapter<LiveRoomAdapter.LiveRoomViewHolder>() {
    private val liveDataList = mutableListOf<LiveRoomData>()
    private var onEnterLiveRoomListener: ((liveData: LiveRoomData, position: Int) -> Unit)? = null

    inner class LiveRoomViewHolder(private val binding: ItemMoreLiveBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(liveData: LiveRoomData, position: Int) {
            // 标签（可根据业务调整）
            binding.tvTag.text = "直播"
            // 主播名
            binding.tvAuthor.text = liveData.room_name ?: "未知主播"
            // 标题/描述
            binding.tvTitle.text = liveData.room_description ?: "暂无简介"
            // 热度
            binding.tvViewers.text = "${liveData.hot ?: 0} 热度"
            // 缩略图（如有专门封面字段请替换 play_url）
            Glide.with(binding.ivThumbnail.context)
                .load(liveData.play_url)
                .centerCrop()
                .transform(CenterCrop(), RoundedCorners(10))
                .into(binding.ivThumbnail)
            // 点击事件
            itemView.setOnClickListener {
                onEnterLiveRoomListener?.invoke(liveData, position)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LiveRoomViewHolder {
        val binding = ItemMoreLiveBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return LiveRoomViewHolder(binding)
    }

    override fun onBindViewHolder(holder: LiveRoomViewHolder, position: Int) {
        holder.bind(liveDataList[position], position)
    }

    override fun getItemCount(): Int = liveDataList.size

    fun setData(data: List<LiveRoomData>) {
        liveDataList.clear()
        liveDataList.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data: List<LiveRoomData>) {
        val startPos = liveDataList.size
        liveDataList.addAll(data)
        notifyItemRangeInserted(startPos, data.size)
    }

    fun setOnEnterLiveRoomListener(listener: (liveData: LiveRoomData, position: Int) -> Unit) {
        onEnterLiveRoomListener = listener
    }
}